package data;

import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Calendar;
import java.util.Random;

/**
 *
 * @author Matthew Poulos
 * This class simply generates a few random values and sends it to the server
 */
public class TestClient {

    public static void main(String[] args) {
        try {
            Socket sock = new Socket("127.0.0.1", 4545);
            DataOutputStream out = new DataOutputStream(sock.getOutputStream());
            //generate some random data
            Random rand = new Random();

            for(int i = 0; i < 6; i++) {
            	//write the length
                int length = 3;//rand.nextInt(3) + 2;
                out.writeShort(length);
                //write the mac and sensor index
                byte mac = (byte)rand.nextInt(5);
                byte index = (byte)rand.nextInt(2);
                byte packedByte = (byte) ((mac << 3) | index);
                out.writeByte(packedByte);
                
                System.out.println(getBinaryString(packedByte));
               
                for(int j = 0; j < length; j++) {
                    //write the current time
                    long time = Calendar.getInstance().getTimeInMillis();
                    out.writeLong(time);
                    
                    //write the value
                    char value = (char)rand.nextInt(Character.MAX_VALUE);
                    out.writeChar(value);

                    
                    Thread.sleep(60);

                }
            }
            out.close();
            
            sock.close();
            
            DatabaseAccessor da = DatabaseAccessor.getInstance();
            Pair<Long,Float>[] points =
                    da.getData("0014.4F01.0000.0735", "Strain", 1236971073349L,
                    Calendar.getInstance().getTimeInMillis());
            for(Pair<Long,Float> p : points) {
                System.out.println(p.fst + ":\t" + p.snd);
            }
            
            

            

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Only used for debugging purposes
     * @param b Byte to parse
     * @return String representation of bits of b
     */
    private static String getBinaryString(byte b) {
        StringBuilder builder = new StringBuilder();
        byte mask = 1;
        for(int i = 0; i < 8; i++) {
            if( (b & mask) == mask) {
                builder.insert(0, "1");
            } else {
                builder.insert(0,"0");
            }
            mask <<= 1;
        }
        return builder.toString();
    }
}
